import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVR
from sklearn.model_selection import train_test_split,GridSearchCV
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import StandardScaler

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

np.random.seed(42)
x=np.sort(5*np.random.rand(100, 1), axis=0)

y=np.sin(x).ravel()

y[::5]+=3*(0.5-np.random.rand(20))

xtrain,xtest,ytrain,ytest=train_test_split(x,y,test_size=0.2,random_state=42)

svr_rbf=SVR()
parameters={'kernel':('linear', 'rbf'), 'C':[1, 10, 100, 1000], 'gamma':('scale', 'auto')}
svr_rbf=GridSearchCV(svr_rbf,parameters,cv=10)

svr_rbf.fit(xtrain,ytrain)

y_pred=svr_rbf.predict(xtest)

mse=mean_squared_error(ytest,y_pred)

print("MSE:",mse)

plt.scatter(x,y,c='k',label='数据点')
plt.plot(x,svr_rbf.predict(x),color='r',label='RBF模型')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()